package com.kele.demo.interceptor;

import com.kele.demo.annotation.AuthToken;
import com.kele.demo.service.impl.LoginUserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author chunhui.li
 * @date 2022/2/14 17:39
 * @Description
 * @ClassName TokenInterceptor
 */
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    LoginUserServiceImpl loginUserService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 从 http 请求头中取出 token
        String token = request.getHeader("token");
        // 如果不是映射到方法直接通过
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod handlerMethod=(HandlerMethod)handler;
        Method method=handlerMethod.getMethod();
        if (method.isAnnotationPresent(AuthToken.class)) {
            AuthToken jwtToken = method.getAnnotation(AuthToken.class);
            if (jwtToken.required()) {
                // 执行认证
                if (token == null) {
                    throw new RuntimeException("无token，请重新登录");
                } else if (loginUserService.checkToken(token)){
                    return true;
                }else {
                    throw new RuntimeException("没有访问权限");
                }
            }
        }
        return false;
    }
}
